package cn.valo.org.controller;

import cn.valo.basic.util.AjaxResult;
import cn.valo.basic.util.PageList;
import cn.valo.org.domain.Department;
import cn.valo.org.query.DepartmentQuery;
import cn.valo.org.service.IDepartmentService;
import cn.valo.system.annotation.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/dept")
public class DepartmentController {
    @Autowired
    private IDepartmentService iDepartmentService;

    static List<Department> querytree;


    //id查询
    @GetMapping("/{id}")
    public Department queryById(@PathVariable("id") Long id){
        return iDepartmentService.queryById(id);
    }
    //查所有
    @GetMapping()
    public List<Department> queryAll(){
        return iDepartmentService.queryAll();
    }
    //高级查询+分页
    @PostMapping
    public PageList<Department> list(@RequestBody DepartmentQuery query){
        System.out.println("-------------");
        System.out.println(query);
        return iDepartmentService.queryPage(query);
    }
    @PreAuthorize(value ="dept:deleteById",name ="删除一条部门数据" )
    @DeleteMapping("/{id}") // /department/1
    public AjaxResult delete(@PathVariable("id") Long id) {
        try {
            iDepartmentService.removeById(id);

            return AjaxResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error();
        }
    }
    @PutMapping //添加或修改
    public AjaxResult addOrUpdate(@RequestBody Department department) {
        System.out.println(department);

        try {
            if (department.getId() != null) {
                iDepartmentService.update(department);
            } else {
                iDepartmentService.save(department);
            }

            return AjaxResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error();
        }

    }

    @PatchMapping
    public AjaxResult delete(@RequestBody List<Long> ids) {
        try {
            iDepartmentService.remove(ids);
            return AjaxResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error();
        }
    }
    @GetMapping("/tree")
    public List<Department> querytree(){
        querytree=   iDepartmentService.querytree();
        System.out.println(querytree);
        return querytree;
    }
}
